package com.djx.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.context.annotation.Bean;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: OSSUtil
 * @Description: TODO
 * @author: 星~
 * @date: 2021/9/29 0029 上午 9:23
 */
public class OSSUtil {

    static final String endpoint = "oss-cn-beijing.aliyuncs.com";
    static final String accessKeyId = "LTAI4G3esuhmnqmbKoEoxf3i";
    static final String accessKeySecret = "EEbCUeB7AHaH2m2HrOEDp8KN74ogz9";
    static final String bucketName = "dun-study";
    static final String imageRootPath = "img/";




    /**
     * 创建OSS客户端
     *
     * @return
     */
    public static OSS OSSClient() {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        return ossClient;
    }

    /**
     * 上传文件
     */
    public static Map<String, Object> uploadImg01(InputStream inputStream, String fileName) {
        Map<String, Object> r = new HashMap<>();
        OSS ossClient = OSSClient();
        fileName = System.currentTimeMillis() + "_" + fileName;
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, imageRootPath + fileName, inputStream);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);
            ossClient.putObject(putObjectRequest);
        } catch (Exception e) {
            r.put("status", false);
            r.put("msg", "上传失败，原因为："+e);
            return r;
        } finally {
            ossClient.shutdown();
        }
        r.put("status", true);
        r.put("url", "https://" + bucketName + "." + endpoint+"/" + imageRootPath + fileName);
        r.put("msg","上传成功!");
        return r;
    }


}
